Java DES(对称加密)

简单一种对称加密与解密
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class DESUtils {

/*
* 生成密钥
*/
public static byte[] initKey() throws Exception {
KeyGenerator keyGen = KeyGenerator.getInstance("DES");
keyGen.init(56);
SecretKey secretKey = keyGen.generateKey();
return secretKey.getEncoded();
}

/*
* DES 加密
*/
public static String encrypt(byte[] data, byte[] key) throws Exception {
SecretKey secretKey = new SecretKeySpec(key, "DES");

Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] cipherBytes = cipher.doFinal(data);
String result = byte2Hex(cipherBytes);
return result;
}

/*
* DES 解密
*/
public static String decrypt(byte[] data, byte[] key) throws Exception {
SecretKey secretKey = new SecretKeySpec(key, "DES");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] plainBytes = cipher.doFinal(data);
String result = new String(plainBytes);
return result;
}

private static int toByte(char c) {
byte b = (byte) "0123456789ABCDEF".indexOf(c);
return b;
}

public static byte[] hexToByte(String hex) {
int len = (hex.length() / 2);
byte[] result = new byte[len];
char[] achar = hex.toCharArray();
for (int i = 0; i < len; i++) {
int pos = i * 2;
result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
}
return result;
}

public static String byte2Hex(byte[] b) {
String stmp = "";
StringBuilder sb = new StringBuilder("");
for (int n = 0; n < b.length; n++) {
stmp = Integer.toHexString(b[n] & 0xFF);
sb.append((stmp.length() == 1) ? "0" + stmp : stmp);
}
return sb.toString().toUpperCase().trim();
}

//加密
public static String encryptStr(String str, String secreytKey) throws Exception {
String enResult = encrypt(str.getBytes(), hexToByte(secreytKey));
return enResult;
}

//解密
public static String decryptStr(String str, String secreytKey) throws Exception {
String deResult = decrypt(hexToByte(str), hexToByte(secreytKey));
return deResult;
}

/***
*
秘钥769bfbae9d20100d
加密结果e3f6b60180661bb0d541de00260afb10
解密结果hello_world
*
* @param args
* @throws Exception
*/

public static void main(String[] args) throws Exception {
//生成秘钥
byte[] desKey = initKey();
String secreytKey = byte2Hex(desKey);
System.out.println("秘钥" + secreytKey.toLowerCase());
//加密
String hello_world = encryptStr("hello_world", secreytKey);
System.out.println("加密结果" + hello_world.toLowerCase());
//解密
String deResult = decryptStr(hello_world, secreytKey);
System.out.println("解密结果" + deResult);

}
}